<template>
  <div class="course-lesson-nav" :class="{ collapsed: isCollapsed }">
    <div class="collapse-toggle" @click="toggleCollapse">
      <el-icon v-if="isCollapsed">
        <ArrowRight />
      </el-icon>
      <el-icon v-else>
        <ArrowLeft />
      </el-icon>
    </div>
    <el-scrollbar v-show="!isCollapsed" height="calc(100vh - 60px)">
      <div v-if="!dataLoaded">
        <el-skeleton :rows="5" animated />
      </div>
      <el-menu v-show="dataLoaded" :default-active="activeIndex" class="course-lesson-menu" @select="handleSelect"
        @open="menuOpened">
        <el-sub-menu v-for="course in courses" :key="course.id" :index="`course-${course.id}`">
          <template #title>
            <el-icon v-if="course.loading === true">
              <Loading />
            </el-icon>
            <el-icon v-if="course.loading === false">
              <Notebook :color="course.id == currentCourseId ? 'green':''"/>
            </el-icon>
            <span
              :style="course.loading === false && course.id == currentCourseId ? 'color:green;font-weight:bold !important;' : ''">{{
                course.title }}</span>
            <el-button text class="course-link" @click="goToCourse(course)" @click.stop>
              进入
            </el-button>
          </template>

          <el-menu-item v-for="lesson in getLessonsForCourse(course.id)" :key="`${course.id}-${lesson.id}`"
            :index="`lesson-${course.id}-${lesson.id}`" class="lesson-item">
            <el-icon v-if="lesson.id == currentLessonId && course.id === currentCourseId">
              <Aim color="green" class="rotate-icon" />
            </el-icon>
            <el-icon v-else>
              <Memo />
            </el-icon>
            <span :style="isCurrentLesson(course, lesson) ? 'color:green;' : ''">
              {{ lesson.order }}. {{ lesson.title }}
            </span>
            <!-- <el-tag v-if="isCurrentLesson(lesson)" type="primary" size="small" effect="dark">学习中</el-tag> -->
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import http from '@/utils/http'
import { ElScrollbar, ElMenu, ElSubMenu, ElMenuItem, ElIcon, ElTag, ElButton } from 'element-plus'
import { Loading, Memo, ArrowLeft, ArrowRight, Aim, Notebook } from '@element-plus/icons-vue'

export default {
  name: 'CourseLessonNav',
  components: {
    ElScrollbar,
    ElMenu,
    ElSubMenu,
    ElMenuItem,
    ElIcon,
    ElTag,
    ElButton,
    Memo,
    ArrowLeft,
    ArrowRight,
    Loading,
    Aim,
    Notebook
  },
  props: {
    currentCourseId: {
      type: [String, Number],
      default: null
    },
    currentLessonId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      courses: [],
      categories: [],
      lessons: {},
      activeIndex: '',
      isCollapsed: true,
      dataLoaded: false
    }
  },
  async created() {
    // 从localStorage获取折叠状态
    this.isCollapsed = localStorage.getItem('courseLessonNavCollapsed') === 'true'
  },
  async mounted() {
    if (!this.dataLoaded && !this.isCollapsed) {
      await this.loadCoursesAndLessons()
      this.dataLoaded = true
    }
    this.updateActiveIndex()
  },
  methods: {
    toggleCollapse() {
      // 将折叠状态切换写入localStorage
      this.isCollapsed = !this.isCollapsed
      localStorage.setItem('courseLessonNavCollapsed', this.isCollapsed)
      if (!this.dataLoaded && !this.isCollapsed) {
        this.loadCoursesAndLessons()
        this.dataLoaded = true
      }
    },

    async loadCoursesAndLessons() {
      try {
        // Load all courses
        const coursesResponse = await http.get('/courses')
        for (let i = 0; i < coursesResponse.length; i++) {
          this.courses = this.courses.concat(coursesResponse[i].courses);
        }
        const that = this;
        // Load lessons for each course
        for (const course of this.courses) {
          course.loading = false;
        }
      } catch (err) {
        console.error('Failed to load courses', err)
      }
    },

    getLessonsForCourse(courseId) {
      return this.lessons[courseId] || []
    },

    isCurrentLesson(course, lesson) {
      return this.currentLessonId && lesson.id == this.currentLessonId && course.id == this.currentCourseId
    },

    goToCourse(course) {
      this.$router.push(`/course/${course.id}`)
    },
    menuOpened(idx) {
      const that = this;
      const str = idx;
      const numbers = str.match(/\d+/g).map(Number);
      const courseID = numbers.join('');
      const c = that.courses.find(c => c.id == courseID)
      if (!c) return;
      c.loading = true;
      try {
        if(this.lessons[c.id] && this.lessons[c.id].length > 0){
          c.loading = false;
          return;
        }
        http.get(`/courses/${courseID}/lessons`).then((dat) => {
          that.lessons[c.id] = dat;
          c.loading = false;
        })
      } catch (err) {
        console.error(`Failed to load lessons for course ${course.id}`, err)
        // In Vue 3, we can directly assign to reactive objects
        this.lessons[c.id] = []
        c.loading = false;
      }
    },
    handleSelect(index) {
      // Handle menu selection
      if (index.startsWith('lesson-')) {
        // Extract course ID and lesson ID from the composite index
        const parts = index.replace('lesson-', '').split('-')
        if (parts.length >= 2) {
          const courseId = parts[0]
          const lessonId = parts.slice(1).join('-') // Join the rest in case lesson ID contains dashes

          const lesson = this.lessons[courseId]?.find((less) => {
            return `${less.id}` === lessonId
          })
          if (lesson) {
            const course = this.courses.find(c => `${c.id}` === courseId)
            if (course) {
              this.$router.push(`/lesson/${encodeURIComponent(course.path)}/${lessonId}`)
            }
          }
        }
      } else if (index.startsWith('course-')) {
        // Handle course selection
        const courseId = index.replace('course-', '')
        const course = this.courses.find(c => `${c.id}` === courseId)
        if (course) {
          this.$router.push(`/course/${encodeURIComponent(course.path)}`)
        }
      }
    },

    updateActiveIndex() {
      if (this.currentLessonId && this.currentCourseId) {
        this.activeIndex = `lesson-${this.currentCourseId}-${this.currentLessonId}`
      } else if (this.currentCourseId) {
        this.activeIndex = `=====:course-${this.currentCourseId}`
      }
    }
  },
  watch: {
    currentLessonId: {
      handler() {
        this.updateActiveIndex()
      },
      immediate: true
    },
    currentCourseId: {
      handler() {
        this.updateActiveIndex()
      }
    }
  }
}
</script>

<style scoped lang="scss">
@use '../../assets/styles/courseLessonNav.scss';
</style>
